package com.example.k8s.hello.service.sys.aspect;

import com.example.k8s.hello.bean.sys.entity.SysLogEntity;
import com.example.k8s.hello.common.annotation.SysLog;
import com.example.k8s.hello.common.utils.HttpContextUtils;
import com.example.k8s.hello.common.utils.IPUtils;
import com.example.k8s.hello.common.utils.JsonUtils;
import com.example.k8s.hello.common.utils.StpExtendUtil;
import com.example.k8s.hello.service.sys.service.SysLogService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 系统日志，切面处理类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Aspect
@Component
@RequiredArgsConstructor
public class SysLogAspect {
	private final SysLogService sysLogService;
	
	@Pointcut("@annotation(com.example.k8s.hello.common.annotation.SysLog)")
	public void logPointCut() { 
		
	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		//执行方法
		Object result = point.proceed();
		//执行时长(毫秒)
		long time = System.currentTimeMillis() - beginTime;

		//保存日志
		saveSysLog(point, time);

		return result;
	}

	private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		SysLogEntity sysLog = new SysLogEntity();
		SysLog syslog = method.getAnnotation(SysLog.class);
		if(syslog != null){
			//注解上的描述
			sysLog.setOperation(syslog.value());
		}

		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLog.setMethod(className + "." + methodName + "()");

		if (syslog != null && syslog.params()) {
			//请求的参数
			Object[] args = joinPoint.getArgs();
			try{
				String params = JsonUtils.toJsonString(args);
				sysLog.setParams(params);
			}catch (Exception e){

			}
		}

		//获取request
		HttpServletRequest request = HttpContextUtils.getRequest();
		//设置IP地址
		sysLog.setIp(IPUtils.getIpAddr(request));

		//学号
		String username = StpExtendUtil.getLoginUser().getUsername();
		sysLog.setUsername(username);

		sysLog.setTime(time);
		//保存系统日志
		sysLogService.save(sysLog);
	}
}
